<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
    <el-form-item label="设备名称" prop="deviceName">
      <el-input
        v-model="queryParams.deviceName"
        placeholder="请输入设备名称"
        clearable
        @keyup.enter="handleQuery"
        class="!w-240px"
      />
    </el-form-item>
    <el-form-item label="型号" prop="model">
      <el-input
        v-model="queryParams.model"
        placeholder="请输入型号"
        clearable
        @keyup.enter="handleQuery"
        class="!w-240px"
      />
    </el-form-item>
    <el-form-item label="设备分类" prop="categoryId">
      <el-tree-select
        v-model="queryParams.categoryId"
        :data="deviceCategoryTree"
        :props="{ ...defaultProps, label: 'categoryName' }"
        check-strictly
        default-expand-all
        placeholder="请选择设备分类"
        class="!w-240px"
      />
    </el-form-item>
    <!-- <el-form-item label="状态（1=在售，0=下架）" prop="status">
      <el-select
        v-model="queryParams.status"
        placeholder="请选择状态（1=在售，0=下架）"
        clearable
        class="!w-240px"
      >
        <el-option label="在售" :value="1" />
        <el-option label="下架" :value="0" />
      </el-select>
    </el-form-item> -->
    <el-form-item label="创建时间" prop="createTime">
      <el-date-picker
        v-model="queryParams.createTime"
        value-format="YYYY-MM-DD HH:mm:ss"
        type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['agent:device:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['agent:device:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="selectedIds.length === 0"
          :loading="batchDeleteLoading"
          @click="handleBatchDelete"
          v-hasPermi="['agent:device:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleDownloadTemplate"
        >
          <Icon icon="ep:document" class="mr-5px" /> 下载模板
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openImportDialog"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      @selection-change="handleSelectionChange"
      ref="tableRef"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="设备分类" align="center" prop="categoryName" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="计量单位" align="center" prop="unit" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === 1">在售</el-tag>
          <el-tag type="info" v-else>下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="deviceImage">
        <template #default="scope">
          <el-image :src="scope.row.deviceImage" style="width: 60px; height: 60px" fit="contain" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="success"
            @click="handleAddToCart(scope.row)"
          >
            加入选装
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['agent:device:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['agent:device:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 右侧选装购物车入口按钮 -->
  <div class="cart-fab">
    <el-badge :value="selectedCart.length">
      <el-button type="primary" circle @click="cartDrawerVisible = true">
        <Icon icon="ep:shopping-cart" />
      </el-button>
    </el-badge>
  </div>

  <!-- 右侧抽屉：选装设备栏 -->
  <ElDrawer v-model="cartDrawerVisible" title="选装设备栏" direction="rtl" size="50%">
    <div class="mb-10px flex items-center justify-between">
      <div class="text-16px font-600">选装设备（{{ selectedCart.length }}）</div>
      <div>
        <el-button type="success" plain :disabled="selectedCart.length === 0" @click="handleExportCart">
          <Icon icon="ep:download" class="mr-5px" /> 下载选装Excel
        </el-button>
        <el-button type="danger" plain :disabled="selectedCart.length === 0" @click="handleClearCart">
          <Icon icon="ep:delete" class="mr-5px" /> 清空选装栏
        </el-button>
      </div>
    </div>
    <el-table :data="selectedCart" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="设备分类" align="center" prop="categoryName" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="计量单位" align="center" prop="unit" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === 1">在售</el-tag>
          <el-tag type="info" v-else>下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="danger" @click="handleRemoveFromCart(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ElDrawer>

  <!-- 表单弹窗：添加/修改 -->
  <DeviceForm ref="formRef" @success="getList" />

  <!-- 导入弹窗 -->
  <Dialog v-model="importDialogVisible" title="导入设备数据" width="500px">
    <div class="mb-10px">
      <el-alert title="请先下载模板，按格式填充再导入" type="info" show-icon />
    </div>
    <el-form label-width="100px">
      <el-form-item label="选择文件">
        <el-upload
          class="upload-demo"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xls,.xlsx"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">仅支持 .xls/.xlsx 文件，最大 10MB</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="是否更新">
        <el-switch v-model="updateSupport" active-text="是" inactive-text="否" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :loading="uploading" @click="handleImportSubmit">开始导入</el-button>
      <el-button @click="closeImportDialog">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceApi, DeviceVO } from '@/api/agent/device/device'
import DeviceForm from './DeviceForm.vue'
import { DeviceCategoryApi } from '@/api/agent/device/devicecategory'
import { defaultProps, handleTree } from '@/utils/tree'

/** 设备信息主 列表 */
defineOptions({ name: 'Device' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceName: undefined,
  model: undefined,
  categoryId: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const deviceCategoryTree = ref([])
const importDialogVisible = ref(false)
const fileList = ref([] as any[])
const selectedFile = ref<File | null>(null)
const updateSupport = ref(false)
const uploading = ref(false)
const tableRef = ref()
const selectedIds = ref<number[]>([])
const batchDeleteLoading = ref(false)
const selectedCart = ref<DeviceVO[]>([])
const cartDrawerVisible = ref(false)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceApi.getDevicePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeviceApi.deleteDevice(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 表格选择变更 */
const handleSelectionChange = (selection: DeviceVO[]) => {
  selectedIds.value = selection.map((item) => item.id)
}

/** 批量删除 */
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) return
  try {
    await message.delConfirm(`是否确认删除选中的设备（共 ${selectedIds.value.length} 条）？`)
    batchDeleteLoading.value = true
    await Promise.all(selectedIds.value.map((id) => DeviceApi.deleteDevice(id)))
    message.success(t('common.delSuccess'))
    selectedIds.value = []
    try { tableRef.value?.clearSelection?.() } catch {}
    await getList()
  } catch {
    // 忽略异常以确保loading复位
  } finally {
    batchDeleteLoading.value = false
  }
}

/** 选装：加入选装栏 */
const handleAddToCart = (row: DeviceVO) => {
  const exists = selectedCart.value.some((item) => item.id === row.id)
  if (exists) {
    message.info('该设备已在选装栏')
    return
  }
  selectedCart.value.push(row)
  message.success('已加入选装栏')
}

/** 选装：从选装栏删除 */
const handleRemoveFromCart = (id: number) => {
  selectedCart.value = selectedCart.value.filter((item) => item.id !== id)
}

/** 选装：清空选装栏 */
const handleClearCart = () => {
  selectedCart.value = []
}

/** 选装：导出选装Excel（前端生成CSV为Excel） */
const handleExportCart = () => {
  if (selectedCart.value.length === 0) {
    message.error('选装栏为空，无法导出')
    return
  }
  const headers = [
    '设备名称',
    '型号',
    '设备分类',
    '供应商',
    '单价',
    '计量单位',
    '状态',
    '备注',
    '图片'
  ]
  const quote = (val: any) => {
    const s = val === undefined || val === null ? '' : String(val)
    return '"' + s.replace(/"/g, '""') + '"'
  }
  const rows = selectedCart.value.map((item) => [
    quote(item.deviceName),
    quote(item.model),
    quote(item.categoryName),
    quote(item.supplierName),
    quote(item.price),
    quote(item.unit),
    quote(item.status === 1 ? '在售' : '下架'),
    quote(item.remark),
    quote(item.deviceImage)
  ])
  const csvContent = '\ufeff' + [headers.join(','), ...rows.map((r) => r.join(','))].join('\r\n')
  download.excel(csvContent as unknown as Blob, '选装设备.xls')
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeviceApi.exportDevice(queryParams)
    download.excel(data, '设备信息主.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 下载导入模板 */
const handleDownloadTemplate = async () => {
  const data = await DeviceApi.importDeviceTemplate()
  download.excel(data, '设备导入模板.xls')
}

/** 打开导入弹窗 */
const openImportDialog = () => {
  importDialogVisible.value = true
}

/** 关闭导入弹窗 */
const closeImportDialog = () => {
  importDialogVisible.value = false
  fileList.value = []
  selectedFile.value = null
  updateSupport.value = false
}

/** 文件选择 */
const handleFileChange = (file: any, fileListParam: any[]) => {
  selectedFile.value = file.raw as File
  fileList.value = fileListParam
}

/** 提交导入 */
const handleImportSubmit = async () => {
  if (!selectedFile.value) {
    message.error('请先选择要导入的文件')
    return
  }
  try {
    uploading.value = true
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('updateSupport', String(updateSupport.value))
    const res = await DeviceApi.importDevice(formData)
    const data = res.data
    const createCount = data.createDeviceNames?.length || 0
    const updateCount = data.updateDeviceNames?.length || 0
    const failureCount = data.failureDeviceNames ? Object.keys(data.failureDeviceNames).length : 0
    message.success(`导入完成：新增 ${createCount}，更新 ${updateCount}，失败 ${failureCount}`)
    closeImportDialog()
    await getList()
  } catch (e) {
  } finally {
    uploading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getDeviceCategoryTree()
})

/** 获得设备分类树 */
const getDeviceCategoryTree = async () => {
  deviceCategoryTree.value = []
  const data = await DeviceCategoryApi.getDeviceCategoryList()
  const root = { id: 0, categoryName: '顶级设备分类', children: [] as any[] }
  root.children = handleTree(data, 'id', 'parentId')
  deviceCategoryTree.value.push(root)
}
</script>

<style scoped>
.cart-fab {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 2000;
}
</style>